package com.taylor.community.event;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.taylor.community.entity.DiscussPost;
import com.taylor.community.entity.Event;
import com.taylor.community.entity.Message;
import com.taylor.community.service.DiscussPostService;
import com.taylor.community.service.ElasticsearchService;
import com.taylor.community.service.MessageService;
import com.taylor.community.util.CommunityConstant;
import com.taylor.community.util.CommunityUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

@Component
public class EventConsumer implements CommunityConstant {
    public static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);
    @Autowired
    private MessageService messageService;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private ElasticsearchService elasticsearchService;
    @Value("${wk.image.storage}")//获取配置文件里面的属性
    private String wkImageStorage;
    @Value("${wk.image.command}")//获取配置文件里面的属性
    private String wkImageCommand;
    @Value("${qiniu.bucket.share.name}")
    private String shareBucketName;
    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;
    @Value("${qiniu.key.access}")
    private String accessKey;
    @Value("${qiniu.key.secret}")
    private String secretKey;
    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;
    //一个消费者可以消费多个主题 一个主题也可以被多个消费者消费
    //写一个方法（相当于一个消费者）消费三个主题（评论、点赞、关注）
    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleTopicsMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息内容为空！");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误！");
            return;
        }
        //系统发送通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());
        Map<String, Object> content = new HashMap<>();
        //事件的触发者
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());
        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        //将content转换为JSON格式字符串
        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }

    /**
     * 发帖事件（将新添的帖子/修改过的帖子同步到es服务器）
     * @param record
     */
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return;
        }
        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());
        elasticsearchService.saveDiscussPost(post);
    }

    /**
     * 删帖事件 将帖子从es服务器删除
     * @param record
     */
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record){
        if(record ==null|| record.value()==null){
            logger.error("消息内容为空!");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(),Event.class);
        if (event == null){
            logger.error("消息格式错误!");
            return;
        }
        elasticsearchService.deleteDiscussPost(event.getEntityId());
    }

    /**
     * 分享操作 生成长图事件
     * @param record
     */
    @KafkaListener(topics = TOPIC_SHARE)
    public void handleShare(ConsumerRecord record){
        if(record ==null|| record.value()==null){
            logger.error("消息内容为空!");
            return;
        }
        Event event = JSONObject.parseObject(record.value().toString(),Event.class);
        if (event == null){
            logger.error("消息格式错误!");
            return;
        }
        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName");
        String suffix = (String) event.getData().get("suffix");
        //执行命令
        String cmd = wkImageCommand + " --quality 70 "
                + htmlUrl + " " + wkImageStorage + "/" + fileName + suffix;
        try {
            Runtime.getRuntime().exec(cmd);
            logger.info("生成长图成功："+cmd);
        } catch (IOException e) {
            logger.error("生成长图失败："+e.getMessage());
        }
        //生成图片需要时间 可能会存在程序执行到以下上传的逻辑时图片还没有生成完毕
        //故用ThreadPoolTaskScheduler类设定一个定时任务 每隔一段时间查看要分享的图片是否生成完毕 是则上传至七牛云
        //Kafka的消费者对于消息有抢占机制 即使在分布式部署情况下 多台服务器上的消费者其实只有一台服务器上的消费者可以消费这个消息
        //因此 在一台服务器上启动这个定时任务跟其他服务器不会产生冲突 故可以使用ThreadPoolTaskScheduler
        //单独写UploadTask类作为线程体
        UploadTask task = new UploadTask(fileName,suffix);
        Future future = taskScheduler.scheduleAtFixedRate(task,500);//每半秒查看一次是否已经生成图片，有则上传图片至七牛云的任务
        task.setFuture(future);
    }
    //匿名实现UploadTask类
    class UploadTask implements Runnable{
        //需要传入文件名称
        private String fileName;
        private String suffix;
        //启动任务的返回值 可以用来停止定时器
        private Future future;
        //开始时间(用于判断超时停止)
        private Long startTime;
        //上传次数(用于判断上传失败)
        private int uploadTimes;

        public void setFuture(Future future) {
            this.future = future;
        }

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }

        @Override
        public void run() {
            //终止条件
            //1.生成图片超时
            if(System.currentTimeMillis() - startTime > 30000){
                logger.error("生成时间过长，无法生成图片，终止任务："+fileName);
                future.cancel(true);//停止定时任务
            }
            //2.上传图片至云服务器失败
            if(uploadTimes >= 3){
                logger.error("图片上传次数过多，终止任务："+fileName);
                future.cancel(true);
            }
            String path = wkImageStorage + "/" + fileName + suffix;
            File file = new File(path);
            if(file.exists()){
                logger.info(String.format("开始第%d次上传【%s】.",++uploadTimes,fileName));
                //设置响应信息 后面自己可以从响应结果中取出 用于判断是否上传成功
                StringMap policy = new StringMap();
                policy.put("returnBody", CommunityUtil.getJSONString(200));
                //生成上传凭证
                Auth auth = Auth.create(accessKey,secretKey);
                String uploadToken = auth.uploadToken(shareBucketName,fileName,3600,policy);
                //指定上传机房
                UploadManager manager = new UploadManager(new Configuration(Zone.zone2()));
                try{
                    //开始上传图片
                    Response response = manager.put(path,fileName,uploadToken,null,"image/"+suffix.replace(".",""),false);
                    //处理响应结果 response.bodyString()是JSON格式字符串
                    JSONObject json = JSONObject.parseObject(response.bodyString());
                    if(json == null || json.get("code")==null || !json.get("code").toString().equals("200")){
                        logger.error("第%d次上传失败【%s】.",uploadTimes,fileName);
                    }else{
                        logger.info(String.format("第%d次上传成功【%s】",uploadTimes,fileName));
                        future.cancel(true);//结束任务
                    }
                }catch (QiniuException e){
                    logger.error("第%d次上传失败【%s】.",uploadTimes,fileName);
                }
            } else{
                logger.info("等待图片【"+fileName+"】生成.");
            }
        }
    }
}
